package cn.px.service.bean;

import cn.hutool.core.collection.CollectionUtil;
import cn.px.common.util.ListUtils;
import cn.px.common.util.MapUtils;
import cn.px.common.util.SpringContextHolder;
import cn.px.dao.dto.workplace.WorkplaceBacklogDTO;
import cn.px.dao.entity.sb.SbAllocateApply;
import cn.px.dao.entity.sb.SbAllocateTask;
import cn.px.dao.entity.sb.SbOil;
import cn.px.dao.entity.store.Store;
import cn.px.dao.entity.upms.SysDept;
import cn.px.dao.enums.SbAllocateTaskAuditType;
import cn.px.dao.enums.SysUserIdentityType;
import cn.px.dao.enums.WorkplaceBacklogDetailTypeEnum;
import cn.px.dao.enums.WorkplaceBacklogTypeEnum;
import cn.px.dao.mapper.sb.SbAllocateApplyMapper;
import cn.px.dao.mapper.sb.SbOilMapper;
import cn.px.dao.util.MessageTemplateUtil;
import cn.px.dao.vo.SysUserVO;
import cn.px.service.event.WorkplaceBacklogEvent;
import cn.px.service.event.WorkplaceBacklogListEvent;
import cn.px.service.store.StoreService;
import cn.px.service.upms.SysDeptService;
import cn.px.service.upms.SysUserDeptService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2019,安徽阡陌网络科技有限公司 All rights reserved.
 */
@Slf4j
@Component
@AllArgsConstructor
public class WorkplaceBacklogUtilBean {

    private final SysUserDeptService sysUserDeptService;

    private final SysDeptService sysDeptService;

    private final SbAllocateApplyMapper sbAllocateApplyMapper;

    private final StoreService storeService;

    private final SbOilMapper sbOilMapper;

    /**
     * 调拨申请任务通知
     *
     * @param task ：
     */
    public void sendMessageAllocateTask(final SbAllocateTask task) {
        try {
            List<SysUserVO> users = null;
            String deptId = task.getDeptId();
            SysDept dept = sysDeptService.getModelById(deptId);
            SbAllocateApply apply = sbAllocateApplyMapper.selectByPrimaryKey(task.getAllocateId());
            if (SbAllocateTaskAuditType.SB_ZG.getValue().equals(task.getAuditType())) {
                // 获取该部门得设备主管
                // 查询该项目部得所有的项目部设备主管
                users = sysUserDeptService.selectByIdentityTypeDept(dept.getDeptId(), SysUserIdentityType.SB_ZG.getValue());
            } else if (SbAllocateTaskAuditType.XMB_SB_ZG.getValue().equals(task.getAuditType())) {
                // 查询该项目部得所有的项目部设备主管
                users = sysUserDeptService.selectByIdentityTypeLikeDeptCode(dept.getDeptCode(), SysUserIdentityType.XMB_SB_ZG.getValue());
            } else if (SbAllocateTaskAuditType.FGS_SB_ZG.getValue().equals(task.getAuditType())) {
                // 查询分公司设备主管
                users = sysUserDeptService.selectByIdentityTypeLikeDeptCode(dept.getDeptCode(), SysUserIdentityType.FGS_SB_ZG.getValue());
            } else if (SbAllocateTaskAuditType.FGS_SB_FG_LD.getValue().equals(task.getAuditType())) {
                // 查询分公司设备分管领导
                users = sysUserDeptService.selectByIdentityTypeLikeDeptCode(dept.getDeptCode(), SysUserIdentityType.FGS_SB_ZG.getValue());
            } else if (SbAllocateTaskAuditType.JT_SB_ZG.getValue().equals(task.getAuditType())) {
                // 查询集团设备主管
                users = sysUserDeptService.selectByIdentityTypeLikeDeptCode(dept.getDeptCode(), SysUserIdentityType.JT_SB_ZG.getValue());
            } else if (SbAllocateTaskAuditType.JT_SB_FG_LD.getValue().equals(task.getAuditType())) {
                // 查询集团设备分管领导
                users = sysUserDeptService.selectByIdentityTypeLikeDeptCode(dept.getDeptCode(), SysUserIdentityType.JT_SB_FG_LD.getValue());
            } else if (SbAllocateTaskAuditType.USER.getValue().equals(task.getAuditType())) {
                users = ListUtils.newArrayList(new SysUserVO().setUserId(task.getUserId()).setRealName(task.getUserName()));
            }
            if (CollectionUtil.isEmpty(users)) {
                return;
            }
            List<String> userIds = users.stream().map(SysUserVO::getUserId).collect(Collectors.toList());
            // 通知消息
            SpringContextHolder.publishEvent(new WorkplaceBacklogEvent(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_ALLOCATE.getValue(),
                    WorkplaceBacklogDetailTypeEnum.SB_ALLOCATE_AUDIT_TASK.getValue(),
                    task.getId(), MessageTemplateUtil.getAllocateTask(apply.getTitle()),
                    null, userIds)));
        } catch (Exception e) {
            log.error("发送站内信异常，调拨申请任务通知,请核实", e);
        }

    }

    /**
     * 调拨申请结果通知
     *
     * @param apply ：
     * @param flag  ：
     */
    public void sendMessageAllocateApplyResult(final SbAllocateApply apply, boolean flag) {
        try {
            // 通知消息
            SpringContextHolder.publishEvent(new WorkplaceBacklogEvent(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_ALLOCATE.getValue(),
                    WorkplaceBacklogDetailTypeEnum.SB_ALLOCATE_APPLY_RESULT.getValue(),
                    apply.getId(), MessageTemplateUtil.getAllocateApplyResult(apply.getTitle(), flag),
                    null, ListUtils.newArrayList(apply.getCreatedUserId()))));
        } catch (Exception e) {
            log.error("发送站内信异常，调拨申请结果通知,请核实", e);
        }

    }

    /**
     * 设备加油审核任务通知
     *
     * @param sbOils :
     */
    public void sendMessageSbOilAuditTask(final List<SbOil> sbOils) {
        try {
            List<WorkplaceBacklogDTO> backlogs = ListUtils.newArrayList(sbOils.size() * 2);
            Map<String, Store> storeMap = MapUtils.newHashMap(sbOils.size());
            // 通知消息
            sbOils.forEach(sbOil -> {
                backlogs.add(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_OIL.getValue(),
                        WorkplaceBacklogDetailTypeEnum.SB_OIL_AUDIT_TASK.getValue(),
                        sbOil.getId(), MessageTemplateUtil.getSbOilTask(sbOil.getSbName(), sbOil.getSbNo()),
                        null, ListUtils.newArrayList(sbOil.getAuditUserId())));
                // 仓库消息通知，查询该仓库的管理员
                String storeId = sbOil.getStoreId();
                Store store = storeMap.get(storeId);
                if (store == null) {
                    store = storeService.getModelById(storeId);
                    storeMap.put(store.getId(), store);
                }
                String userId = store.getUserId();
                backlogs.add(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_OIL.getValue(),
                        WorkplaceBacklogDetailTypeEnum.SB_OIL_OIL.getValue(),
                        sbOil.getId(), MessageTemplateUtil.getSbOilOil(sbOil.getSbName(), sbOil.getSbNo()),
                        null, ListUtils.newArrayList(userId)));
            });
            SpringContextHolder.publishEvent(new WorkplaceBacklogListEvent(backlogs));
        } catch (Exception e) {
            log.error("发送站内信异常，设备加油通知,请核实", e);
        }

    }

    /**
     * 设备加油审核任务通知
     *
     * @param ids  :
     * @param flag :
     */
    public void sendMessageSbOilAuditResult(final List<String> ids, boolean flag) {
        try {
            Weekend<SbOil> weekend = new Weekend<>(SbOil.class);
            WeekendCriteria<SbOil, Object> weekendCriteria = weekend.weekendCriteria();
            weekendCriteria.andIn(SbOil::getId, ids);
            List<SbOil> sbOils = sbOilMapper.selectByExample(weekend);
            List<WorkplaceBacklogDTO> backlogs = ListUtils.newArrayList(sbOils.size() * 2);
            Map<String, Store> storeMap = MapUtils.newHashMap(sbOils.size());
            sbOils.forEach(sbOil -> {
                // 通知申请人，审批已通过
                backlogs.add(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_OIL.getValue(),
                        WorkplaceBacklogDetailTypeEnum.SB_OIL_AUDIT_RESULT.getValue(),
                        sbOil.getId(), MessageTemplateUtil.getSbOilAuditResult(sbOil.getSbName(), sbOil.getSbNo(), flag),
                        null, ListUtils.newArrayList(sbOil.getCreatedUserId())));
                if (flag) {
                    // 通知油管加油
                    // 仓库消息通知，查询该仓库的管理员
                    String storeId = sbOil.getStoreId();
                    Store store = storeMap.get(storeId);
                    if (store == null) {
                        store = storeService.getModelById(storeId);
                        storeMap.put(store.getId(), store);
                    }
                    String userId = store.getUserId();
                    backlogs.add(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_OIL.getValue(),
                            WorkplaceBacklogDetailTypeEnum.SB_OIL_OIL.getValue(),
                            sbOil.getId(), MessageTemplateUtil.getSbOilOil(sbOil.getSbName(), sbOil.getSbNo()),
                            null, ListUtils.newArrayList(userId)));
                }

            });
            // 通知消息
            SpringContextHolder.publishEvent(new WorkplaceBacklogListEvent(backlogs));
        } catch (Exception e) {
            log.error("发送站内信异常，设备加油通知,请核实", e);
        }

    }

    /**
     * 设备加油 已加油，通知申请人
     *
     * @param ids :
     */
    public void sendMessageSbOilConfirm(final List<String> ids) {
        try {
            Weekend<SbOil> weekend = new Weekend<>(SbOil.class);
            WeekendCriteria<SbOil, Object> weekendCriteria = weekend.weekendCriteria();
            weekendCriteria.andIn(SbOil::getId, ids);
            List<SbOil> sbOils = sbOilMapper.selectByExample(weekend);
            List<WorkplaceBacklogDTO> backlogs = ListUtils.newArrayList(sbOils.size() * 2);
            sbOils.forEach(sbOil -> {
                backlogs.add(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_OIL.getValue(),
                        WorkplaceBacklogDetailTypeEnum.SB_OIL_OIL_CONFIRM.getValue(),
                        sbOil.getId(), MessageTemplateUtil.getSbOilConfirm(sbOil.getSbName(), sbOil.getSbNo()),
                        null, ListUtils.newArrayList(sbOil.getCreatedUserId())));
            });
            // 通知消息
            SpringContextHolder.publishEvent(new WorkplaceBacklogListEvent(backlogs));
        } catch (Exception e) {
            log.error("发送站内信异常，设备加油通知,请核实", e);
        }

    }

    /**
     * 设备加油审核任务通知
     *
     * @param sbOil :
     */
    public void sendMessageSbOilConfirm(final SbOil sbOil) {
        try {
            // 通知消息
            SpringContextHolder.publishEvent(new WorkplaceBacklogEvent(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_OIL.getValue(),
                    WorkplaceBacklogDetailTypeEnum.SB_OIL_OIL.getValue(),
                    sbOil.getId(), MessageTemplateUtil.getSbOilConfirm(sbOil.getSbName(), sbOil.getSbNo()),
                    null, ListUtils.newArrayList(sbOil.getCreatedUserId()))));
        } catch (Exception e) {
            log.error("发送站内信异常，设备加油通知,请核实", e);
        }

    }

    /**
     * 设备加油 确认通知
     *
     * @param ids :
     */
    public void sendMessageSbOilConfirmResult(final List<String> ids) {
        try {
            Weekend<SbOil> weekend = new Weekend<>(SbOil.class);
            WeekendCriteria<SbOil, Object> weekendCriteria = weekend.weekendCriteria();
            weekendCriteria.andIn(SbOil::getId, ids);
            List<SbOil> sbOils = sbOilMapper.selectByExample(weekend);
            List<WorkplaceBacklogDTO> backlogs = ListUtils.newArrayList(sbOils.size() * 2);
            Map<String, Store> storeMap = MapUtils.newHashMap(sbOils.size());
            sbOils.forEach(sbOil -> {
                // 通知油管加油
                // 仓库消息通知，查询该仓库的管理员
                String storeId = sbOil.getStoreId();
                Store store = storeMap.get(storeId);
                if (store == null) {
                    store = storeService.getModelById(storeId);
                    storeMap.put(store.getId(), store);
                }
                String userId = store.getUserId();
                backlogs.add(new WorkplaceBacklogDTO(WorkplaceBacklogTypeEnum.SB_OIL.getValue(),
                        WorkplaceBacklogDetailTypeEnum.SB_OIL_OIL_CONFIRM.getValue(),
                        sbOil.getId(), MessageTemplateUtil.getSbOilConfirmResult(sbOil.getSbName(), sbOil.getSbNo()),
                        null, ListUtils.newArrayList(userId)));

            });
            // 通知消息
            SpringContextHolder.publishEvent(new WorkplaceBacklogListEvent(backlogs));
        } catch (Exception e) {
            log.error("发送站内信异常，设备加油通知,请核实", e);
        }

    }
}
